import { ConfigEnv, UserConfigExport, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import viteCompression from 'vite-plugin-compression'

/** 路径查找 */
const pathResolve = (dir: string): string => {
  return resolve(__dirname, '.', dir)
}

/** 当前执行node命令时文件夹的地址（工作目录） */
const root: string = process.cwd()
/** 设置别名 */
const alias: Record<string, string> = {
  '@': pathResolve('src'),
  '@build': pathResolve('build')
}
export default ({ command, mode }: ConfigEnv): UserConfigExport => {
  return {
    base: '/cloud-music/',
    resolve: {
      alias
    },
    root,
    // 服务端渲染
    plugins: [
      vue(),
      AutoImport({
        resolvers: [
          ElementPlusResolver({
            importStyle: 'sass'
          })
        ]
      }),
      Components({
        resolvers: [
          ElementPlusResolver({
            importStyle: 'sass'
          })
        ]
      }),
      viteCompression({
        filter: /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i, // 需要压缩的文件
        threshold: 1024, // 文件容量大于这个值进行压缩
        algorithm: 'gzip', // 压缩方式
        ext: 'gz', // 后缀名
        deleteOriginFile: false // 压缩后是否删除压缩源文件
      })
    ],
    optimizeDeps: {
      include: [
        'vue',
        'element-plus/es',
        'element-plus/es/components/config-provider/style/index',
        'element-plus/es/components/pagination/style/index',
        'element-plus/es/components/table/style/index',
        'element-plus/es/components/table-column/style/index',
        'element-plus/es/components/button/style/index',
        'element-plus/es/components/menu/style/index',
        'element-plus/es/components/sub-menu/style/index',
        'element-plus/es/components/menu-item/style/index',
        'element-plus/es/components/carousel/style/index',
        'element-plus/es/components/carousel-item/style/index',
        'element-plus/es/components/button-group/style/index',
        '@element-plus/icons-vue',
        'pinia',
        'axios',
        'vue-router',
        '@vueuse/core',
        '@any-touch/core',
        '@any-touch/pan',
        'dayjs',
        'path'
      ]
    },
    build: {
      sourcemap: false,
      outDir: 'cloud-music',
      // 消除打包大小超过500kb警告
      chunkSizeWarningLimit: 4000,
      rollupOptions: {
        input: {
          index: pathResolve('index.html')
        },
        // 静态资源分类打包
        output: {
          chunkFileNames: 'static/js/[name]-[hash].js',
          entryFileNames: 'static/js/[name]-[hash].js',
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]'
        }
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@use "@/assets/scss/theme.scss" as *;'
        }
      }
    }
  }
}
